package com.ucode.application.config;

import javax.annotation.Resource;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.ucode.springboot.starter.db.config.DruidDataSourcesConfig;

@Configuration
@MapperScan(basePackages = {"com.ucode.*.mapper"},sqlSessionTemplateRef = "defaultSqlSessionTemplate")
public class DefaultDataSourcesConfig{

    @Resource
    private DefaultDataSourcesParam param; 
    
    @Bean("defaultDataSource")
    @Primary
    public DataSource dataSource() {
        return DruidDataSourcesConfig.getDataSource(param);
    }
    
    @Bean(name="defaultSqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("defaultDataSource") DataSource dataSource) throws Exception{
        String mapperLocations ="classpath*:/mapper/*Mapper.xml";
        return DruidDataSourcesConfig.getSqlSessionFactory(dataSource, mapperLocations);
    }
    
    @Bean(name="defaultTransactionManager")
    @Primary
    public DataSourceTransactionManager transactionManager(@Qualifier("defaultDataSource") DataSource dataSource){
        return  DruidDataSourcesConfig.getTransactionManager(dataSource);
    }
    
    @Bean(name = "defaultSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("defaultSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return DruidDataSourcesConfig.getSqlSessionTemplateOne(sqlSessionFactory);
    }
    
}
